package com.cy.mall.web.comm;

import com.cy.mall.comm.constant.Constants;
import com.cy.mall.comm.utils.CommonUtils;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.comm.utils.RSAUtils;
import com.cy.mall.model.Result;
import com.cy.mall.model.dto.fujue.FujueResultDTO;
import com.cy.mall.model.dto.fujue.req.GetH5AddressParamDTO;
import com.cy.mall.model.dto.fujue.resp.LoanApplyDataDTO;
import com.cy.mall.model.dto.fujue.resp.LoanDataDTO;
import com.cy.mall.model.dto.fujue.resp.NotifyDataDTO;
import com.cy.mall.model.enums.MessageType;
import com.cy.mall.model.enums.ThirdSource;
import com.cy.mall.model.enums.order.OrderFinalStatusE;
import com.cy.mall.service.dda.DdaService;
import com.cy.mall.service.fujue.FujueApiService;
import com.cy.mall.service.message.MessageService;
import com.cy.mall.service.order.OrderService;
import com.cy.mall.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Description 对接富爵api
 * @Author tanyilin
 * @Date 2019/3/25 11:01
 */
@Slf4j
@RestController
@RequestMapping("/api/fj")
@Api(tags = "对接富爵api")
public class FujueController extends BaseController {

    @Autowired
    private FujueApiService fujueApiService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private DdaService ddaService;

    @ApiOperation("获取富爵h5地址")
    @GetMapping("/get/h5/address")
    public Result getH5Address(GetH5AddressParamDTO paramDTO) {

        Result<Map<String, Object>> result = fujueApiService.getH5Address(paramDTO);
        return result;
    }

    @ApiOperation("进件数据推送")
    @PostMapping("/push/loan/apply/data")
    public FujueResultDTO pushLoanApplyData(@RequestBody Map<String, Object> paramMap) {

        log.info("推送的进件数据：{}", paramMap);

        String encryptData = String.valueOf(paramMap.get("data"));
        log.info("进件数据推送 api，请求参数data密文：{}", encryptData);

        String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("进件数据推送 api，请求参数data明文：{}", decryptData);

        LoanApplyDataDTO applyData = JsonObjectMapper.read(decryptData, LoanApplyDataDTO.class);
        log.info("Json -----------> javaBean [LoanApplyDataDTO] = {}", applyData);

        //保存进件数据
        orderService.saveApplyData(applyData, ThirdSource.YUNKEDAI);

        return FujueResultDTO.success("推送成功");
    }

    @ApiOperation("获取进件数据")
    @GetMapping("/query/loan/apply/data")
    public Result<Map<String, Object>> queryLoanApplyData(@RequestParam(value = "userId") String userId, @RequestParam(value = "productType") String productType) {

        Result<Map<String, Object>> result = fujueApiService.queryLoanApplyData(userId, productType);
        if(!result.isOk()) {
            return result;
        }

        Map<String, Object> paramMap = result.getData();
        String encryptData = String.valueOf(paramMap.get("data"));
        log.info("获取进件数据 api，返回参数data密文：{}", encryptData);

        String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("获取进件数据 api，返回参数data明文：{}", decryptData);

        LoanApplyDataDTO applyData = JsonObjectMapper.read(decryptData, LoanApplyDataDTO.class);
        if("0000".equals(applyData.getRtCode())) {
            //保存进件数据
            orderService.saveApplyData(applyData, ThirdSource.YUNKEDAI);
        }

        return ok("", applyData);
    }

    @ApiOperation("贷款数据推送")
    @PostMapping("/push/loan/data")
    public FujueResultDTO pushLoanData(@RequestBody Map<String, Object> paramMap) {

        log.info("推送的贷款数据：{}", paramMap);

        String encryptData = String.valueOf(paramMap.get("data"));
        log.info("贷款数据推送 api，请求参数data密文：{}", encryptData);

        String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("贷款数据推送 api，请求参数data明文：{}", decryptData);
        //解析明文data
        LoanDataDTO loanData = JsonObjectMapper.read(decryptData, LoanDataDTO.class);
        log.info("Json -----------> javaBean [LoanDataDTO] = {}", loanData);

        //保存更新贷款数据
        Result saveResult =  orderService.saveLoanData(loanData, ThirdSource.YUNKEDAI);
        if(saveResult.isOk()) {
            OrderFinalStatusE finalStatus = (OrderFinalStatusE) saveResult.getData();
            switch (finalStatus) {
                case DECISION_PASS: //云科通知 审批通过，即马先生显示为 '授信审批`通过'
                    // 微信发送通知
                    messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_DECISION_PASS);
                    break;

                case DECISION_REJECT: //云科通知 审批拒绝，即马先生显示为 '授信审批拒绝'
                    // 微信发送通知
                    messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_DECISION_REJECT);
                    break;

                case LOAN_SUCCESS: //云科通知 放款成功
                    // 微信发送通知
                    messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                    break;

                default:
                    break;
            }
        }

        return FujueResultDTO.success("推送成功");
    }

    @ApiOperation("获取贷款数据")
    @GetMapping("/query/loan/data")
    public Result<Map<String, Object>> queryLoanData(@RequestParam(value = "loanId") String loanId) {

        Result<Map<String, Object>> result = fujueApiService.queryLoanData(loanId);
        if(!result.isOk()) {
            return result;
        }

        Map<String, Object> paramMap = result.getData();
        String encryptData = String.valueOf(paramMap.get("data"));
        log.info("获取贷款数据 api，返回参数data密文：{}", encryptData);

        String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("获取贷款数据 api，返回参数data明文：{}", decryptData);

        LoanDataDTO loanData = JsonObjectMapper.read(decryptData, LoanDataDTO.class);
        if("0000".equals(loanData.getRtCode())) {
            //保存更新贷款数据
            Result saveResult =  orderService.saveLoanData(loanData, ThirdSource.YUNKEDAI);
            if(saveResult.isOk()) {
                OrderFinalStatusE finalStatus = (OrderFinalStatusE) saveResult.getData();
                switch (finalStatus) {
                    case DECISION_PASS: //云科通知 审批通过，即马先生显示为 '授信审批`通过'
                        // 微信发送通知
                        messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_DECISION_PASS);
                        break;

                    case DECISION_REJECT: //云科通知 审批拒绝，即马先生显示为 '授信审批拒绝'
                        // 微信发送通知
                        messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_DECISION_REJECT);
                        break;

                    case LOAN_SUCCESS: //云科通知 放款成功
                        // 微信发送通知
                        messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                        break;

                    default:
                        break;
                }
            }
        }

        return ok("", loanData);
    }

    @ApiOperation("云科回调通知马先生的入口")
    @PostMapping("/notify")
    public FujueResultDTO toNotify(@RequestBody Map<String, Object> paramMap) {

        log.info("云科回调通知的数据：{}", paramMap);
        //Rsa解密
        String encryptData = String.valueOf(paramMap.get("data"));
        log.info("云科回调通知 api，请求参数data密文：{}", encryptData);
        String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("云科回调通知 api，请求参数data明文：{}", decryptData);
        //解析明文data
        NotifyDataDTO notifyData = JsonObjectMapper.read(decryptData, NotifyDataDTO.class);
        log.info("Json -----------> javaBean [NotifyDataDTO] = {}", notifyData);

        //更新订单数据
        Result updateResult = orderService.doUpdateOrderData(notifyData);
        //发送微信消息通知
        if(updateResult.isOk()) {
            OrderFinalStatusE finalStatus = (OrderFinalStatusE) updateResult.getData();
            switch (finalStatus) {
                case ADMISSION_PASS:
                    //'准入额度通过'， 微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_ADMISSION_PASS);
                    break;
                case ADMISSION_REJECT:
                    //'准入额度拒绝'， 微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_ADMISSION_REJECT);
                    break;
                case SIGN_WAIT:
                    //'资料审核通过-去签约'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_MATERIAL_AUDIT_PASS);
                    break;
                case MATERIAL_AUDIT_REJECT:
                    //'资料审核拒绝'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_MATERIAL_AUDIT_REJECT);
                    break;
                case LOAN_SUCCESS:
                    //'放款成功'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                    //同时将该订单信息同步给贷贷安系统，进行尽调
                    ddaService.pushLoanOrderInfo(notifyData.getLoanId());
                    break;
                case REPAYING:
                    //'放款成功-还款中'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                    //同时将该订单信息同步给贷贷安系统，进行尽调
                    ddaService.pushLoanOrderInfo(notifyData.getLoanId());
                    break;
                default:
                    break;
            }
        }

        return FujueResultDTO.success("回调成功");
    }

    @ApiOperation("获取订单数据")
    @GetMapping("/get/order/info")
    public Result<Map<String, Object>> getOrderInfo(@RequestParam(value = "loanId") String loanId) {

//        ddaService.pushLoanOrderInfo(loanId);
//        return ok();

        Result<Map<String, Object>> result = fujueApiService.getOrderInfo(loanId);
        if(!result.isOk()) {
            return result;
        }

        Map<String, Object> paramMap = result.getData();
        //Rsa解密
        String encryptData = String.valueOf(paramMap.get("data"));
        log.info("获取订单数据 api，请求参数data密文：{}", encryptData);
        String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("获取订单数据 api，请求参数data明文：{}", decryptData);
        //解析明文data
        NotifyDataDTO notifyData = JsonObjectMapper.read(decryptData, NotifyDataDTO.class);
        log.info("Json -----------> javaBean [NotifyDataDTO] = {}", notifyData);

        //更新订单数据
        Result updateResult = orderService.doUpdateOrderData(notifyData);
        //发送微信消息通知
        if(updateResult.isOk()) {
            OrderFinalStatusE finalStatus = (OrderFinalStatusE) updateResult.getData();
            switch (finalStatus) {
                case ADMISSION_PASS:
                    //'准入额度通过'， 微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_ADMISSION_PASS);
                    break;
                case ADMISSION_REJECT:
                    //'准入额度拒绝'， 微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_ADMISSION_REJECT);
                    break;
                case SIGN_WAIT:
                    //'资料审核通过-去签约'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_MATERIAL_AUDIT_PASS);
                    break;
                case MATERIAL_AUDIT_REJECT:
                    //'资料审核拒绝'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_MATERIAL_AUDIT_REJECT);
                    break;
                case LOAN_SUCCESS:
                    //'放款成功'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                    //同时将该订单信息同步给贷贷安系统，进行尽调
                    ddaService.pushLoanOrderInfo(notifyData.getLoanId());
                    break;
                case REPAYING:
                    //'放款成功-还款中'，微信发送通知
                    messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                    //同时将该订单信息同步给贷贷安系统，进行尽调
                    ddaService.pushLoanOrderInfo(notifyData.getLoanId());
                    break;
                default:
                    break;
            }
        }

        return ok("获取订单数据成功", notifyData);
    }

    @ApiOperation("测试私钥解密")
    @GetMapping("/test/privateDecrypt")
    public String privateDecrypt() {
        String data = "HDBTxaylw30M5ScsaZgqz2f0n8haxDEVheN5Pjioo50HEbKGC66m7T7I8FkhuVYggFlveeRtg0G75ocRelqFYhbRVBRdRlIB9ryQsut9dEAlUUwXexjy6rJ/Hqq5Rf5Ny8MhNW+JUdLDo0xhVhPLtcbxjQPEdW2X1CM5llQCoj0=";
        log.info("私钥：{}", Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("密文：{}", data);

        return RSAUtils.privateDecrypt(data, Constants.FUJUE_RSA_PRIVATE_KEY);

    }



}
